

module("Db", package.seeall )

PlayerDb = PlayerDb or {}
PlayerDbMeta = PlayerDbMeta or {
	__index = PlayerDb
}

function NewPlayer( ply )
	
	local o = {
		Player = ply
	}
	
	setmetatable( o, PlayerDbMeta )
	
	return o
	
end


function PlayerDb:Select()

	if not Router.Connected then
		self:LoadNew()
		return
	end
	
	local request = {plyId=self:GetPlyId()}
	local plydb = self
	
	PlayerHandler:SendHook("getPlayer", request, function( err, data )
		
		if err then
			print("Err:", err )
		end
		
		plydb:Load( data.data )

	end )
	
end

function PlayerDb:Load( data )
	
	if not data then
		self:LoadNew()
		return
	end
	
	print("Got player data")
	PrintTable( data )
	
	for _, document in ipairs( Db.DocumentList ) do
		
		if data[ document.name ] then
			SafeCall( document.LoadPlayer, document, self.Player, data[ document.name ] )
		else
			SafeCall( document.NewPlayer, document, self.Player )
		end
		
		
	end
	
end

function PlayerDb:LoadNew()
	
	for _, document in ipairs( Db.DocumentList ) do
		
		SafeCall( document.NewPlayer, document, self.Player )
		
	end

end

function PlayerDb:Save()

	if not Router.Connected then
		return
	end

	local SaveCommand = {}
	
	for _, document in ipairs( DocumentList ) do
	
		local b, retn = SafeCall( document.SavePlayer, document, self.Player )

		if b and retn then
			table.Merge( SaveCommand, retn )
		end
	
	end
	
	if table.Count( SaveCommand ) == 0 then
		return
	end
	
	self:SaveRequest( SaveCommand )

end

function PlayerDb:SaveRequest( command )
	
	local request = {
		plyId = self:GetPlyId(),
		command = command
	}
	
	PlayerHandler:SendHook("updatePlayer", request, function( err, data )
		
		if err then
			print("Err:", err )
		end

	end )

end

function PlayerDb:GetPlyId()
	
	if !self._SqlID then
		
		local SteamId = self.Player:SteamID()
		local Findings = {}
		
		for w in string.gmatch( SteamId , "%d+") do
			table.insert( Findings, w )
		end
		
		if #Findings == 3 then
			self._SqlID = (tonumber(Findings[3]) * 2) + tonumber(Findings[2])
		else
			if SteamId != "STEAM_ID_PENDING" && SteamId != "UNKNOWN" then
				print( 'error', "sql id could not be found (".. tostring(SteamId) ..")\n" )
			end
			self._SqlID = 1
		end
		
	end

	return self._SqlID
	
end
